<template>
	<view class="smsCode-container">
		<div class="sms-btn" :style="timer !== null ? 'background: #D2D9E1;' : ''">
			{{ yzmTip }}
		</div>
	</view>
</template>

<script>
	const sms_seconds = 60;
	let defaultTip = "获取验证码";
	export default {
		name: "smsCode",
		data() {
			return {
				yzmTip: defaultTip,
				timerNum: sms_seconds,
				timer: null,
				canGetCode: true, // 是否可以执行验证码操作
			};
		},
		beforeDestroy() {
			this.reset()
		},
		methods: {
			// 倒计时
			start() {
				if (!this.canGetCode) return;

				// 防止快速点击获取验证码的按钮而导致内部产生多个定时器导致混乱
				if (this.timer) {
					clearTimeout(this.timer);
					this.timer = null;
				}
				this.canGetCode = false;
				const timingTask = () => {
					this.timer = setTimeout(() => {
						if (this.timerNum >= 0) {
							this.yzmTip = this.timerNum + '秒';
							timingTask();
							this.timerNum--;
						} else {
							this.reset();
							this.yzmTip = '重新获取';
						}
					}, 1000)
				}
				timingTask()
			},

			reset() {
				clearTimeout(this.timer);
				this.timer = null;
				this.timerNum = sms_seconds;
				this.yzmTip = defaultTip;
				this.canGetCode = true;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.smsCode-container {
		.sms-btn {}
	}
</style>